package com.fuego.creditsystemcommodity.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuego.creditsystemcommodity.mapper.OwnerMapper;
import com.fuego.creditsystemcommodity.service.IOwnerService;
import jakarta.annotation.Resource;
import org.example.dto.Result;
import org.example.entity.Owner;
import org.example.utils.CacheClient;
import org.example.utils.SystemConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

import static org.example.utils.RedisConstants.*;


@Service
public class OwnerServiceImpl extends ServiceImpl<OwnerMapper, Owner> implements IOwnerService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;
    @Override
    public Result queryById(Long id) {
        //解决缓存穿透
        //Owner owner = queryWithPassThrough(id);
        //互斥锁解决缓存穿透
        //Owner owner = queryWithMutex(id);
        //逻辑过期解决缓存穿透

        Owner owner =cacheClient
                .queryWithLogicalExpire(CACHE_OWNER_KEY,LOCK_OWNER_KEY,id, Owner.class,this::getById,CACHE_OWNER_TTL,TimeUnit.MINUTES);
        if(owner==null)
        {
            return Result.fail("店铺不存在！");
        }
        // 返回
        return Result.ok(owner);
    }

    @Override
    @Transactional
    public Result update(Owner owner) {
        Long id= owner.getId();
        if(id==null)
        {
            return Result.fail("商铺id不能为空");
        }
        //1更新数据库
        updateById(owner);
        String key=CACHE_OWNER_KEY+owner.getId();
        stringRedisTemplate.delete(key);
        // 2删除缓存
        return Result.ok();
    }

    @Override
    public Result queryByType(Integer typeId, Integer current) {
        //1判断是否需要根据坐标查询

            Page<Owner> page=query()
                    .eq("type_id",typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            //返回数据
            return Result.ok(page.getRecords());
    }
}
